require 'rexml/document'

module RSS
  include REXML


  def parse(body,feed)

    xml = Document.new(body)

    feed.link         = match(xml, "//channel/link/text()")
    feed.title        = match(xml,  "//channel/title/text()")
    tmp = item_list(xml,feed)
    feed.subscriptions.each do |subscription|
      subscription.items << tmp
    end
    return feed
  end

  private

  def match(elem, path)
      XPath.match(elem, path).first.value rescue ""
  end

  def parse_time(elem)
    Time.mktime(*ParseDate.parsedate(match(elem, "pubDate/text()"))) rescue Time.now
  end

  def parse_item(elem)
    Item.new(:title =>  match(elem,  "title/text()"),
             :link =>  match(elem,  "link/text()"),
             :description =>  match(elem,  "description/text()"),
             :date => parse_time(elem))
  end

  def item_list(xml,feed)
    XPath.match(xml, "//item/").map {|elem| parse_item(elem)}.find_all{ |item| !feed.items.find(:first, :conditions => ["link = ?",item.link])}.map do |item|
      item.feed_id = feed.id
      item.save
    end
  end

end


